package com.laiyima.zhongjiang.linghuilv.demo.home;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.fragment.app.Fragment;

import com.king.zxing.Intents;
import com.king.zxing.util.CodeUtils;
import com.laiyima.zhongjiang.linghuilv.demo.R;
import com.laiyima.zhongjiang.linghuilv.demo.newzxing.CaptureFragmentActivity;
import com.laiyima.zhongjiang.linghuilv.demo.newzxing.UriUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.CenterPopupView;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass.
  * create an instance of this fragment.
 */
public class BingmachineFragment extends Fragment implements View.OnClickListener , EasyPermissions.PermissionCallbacks{
    private String TAG="BingmachineFragment";
    private int bmCode;
    private TextView bing_inputsn;
    private EditText bing_dsec;
    private Button bing_checksn,bing_button,button_fail,button_ok;
    private LinearLayout bing_ing,bing_onSuccess,bing_fail;
    private ImageView saoma_sn;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_bingmachine, container, false);
        bing_inputsn=view.findViewById(R.id.bing_inputsn);
        bing_dsec=view.findViewById(R.id.bing_dsec);
        bing_checksn=view.findViewById(R.id.bing_checksn);
        bing_button=view.findViewById(R.id.bing_button);
        bing_checksn.setOnClickListener(this);
        bing_button.setOnClickListener(this);
        saoma_sn=view.findViewById(R.id.saoma_sn);
        saoma_sn.setOnClickListener(this);

        bing_ing=view.findViewById(R.id.bing_ing);
        bing_ing.setVisibility(View.VISIBLE);
        bing_onSuccess=view.findViewById(R.id.bing_onSuccess);
        bing_onSuccess.setVisibility(View.GONE);
        bing_fail=view.findViewById(R.id.bing_fail);
        bing_fail.setVisibility(View.GONE);
        button_fail=view.findViewById(R.id.button_fail);
        button_fail.setOnClickListener(this);
        button_ok=view.findViewById(R.id.button_ok);
        button_ok.setOnClickListener(this);
        return view;
    }

    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.bing_checksn:
                String sn=bing_inputsn.getText().toString();
                check(sn);
                break;
            case R.id.button_fail:
                bing_ing.setVisibility(View.VISIBLE);
                bing_onSuccess.setVisibility(View.GONE);
                bing_fail.setVisibility(View.GONE);
                break;
            case R.id.button_ok:
                bing_ing.setVisibility(View.VISIBLE);
                bing_onSuccess.setVisibility(View.GONE);
                bing_fail.setVisibility(View.GONE);
                break;
            case R.id.bing_button:
                String mysn=bing_inputsn.getText().toString();
                String mydsec=bing_dsec.getText().toString();
                 bingmachind(mysn,mydsec);
                break;
            case  R.id.saoma_sn:
                this.cls = CaptureFragmentActivity.class;
                this.title = "机具扫码";
                checkCameraPermissions();
                break;
        }

    }

    private void bingmachind(String mysn, String mydsec) {
        SharedPreferences sharedPreferences =getContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/bindingsn");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("sn", mysn);
        params.addBodyParameter("desc", mydsec);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    bmCode = jsonObject.optInt("code", 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (bmCode == 200) {
                    //ok
                    bing_ing.setVisibility(View.GONE);
                    bing_onSuccess.setVisibility(View.VISIBLE);
                    bing_fail.setVisibility(View.GONE);
                }
                if (bmCode == 201) {
                    //fail不存在
                    bing_ing.setVisibility(View.GONE);
                    bing_fail.setVisibility(View.VISIBLE);
                    bing_onSuccess.setVisibility(View.GONE);
                }
                if (bmCode == 404) {
                    //绑定失败
                    bing_ing.setVisibility(View.GONE);
                    bing_fail.setVisibility(View.VISIBLE);
                    bing_onSuccess.setVisibility(View.GONE);
                }
                if(bmCode == 203){
                    //备注限制30个字之内
                    Toast.makeText(getContext().getApplicationContext(), "备注限制30个字之内", Toast.LENGTH_SHORT).show();
                }
                if(bmCode == 202){
                    //该机具已绑定
                    Toast.makeText(getContext().getApplicationContext(), "该机具已绑定", Toast.LENGTH_SHORT).show();
                }
                if(bmCode == 500){
                    //系统异常
                    Toast.makeText(getContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                // Log.e(TAG, "查看实名认证失败");
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {
            }
        });
    }

    private void check(String sn) {
        SharedPreferences sharedPreferences =getContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/check");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("sn", sn);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    bmCode = jsonObject.optInt("code", 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (bmCode == 200) {
                    dialog_show();
                 }
                if (bmCode == 201) {
                    dialog_fail_show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                // Log.e(TAG, "查看实名认证失败");
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {
            }
        });
    }

    private void dialog_show() {
        BingmachineFragment.CustomPopup customPopup = new BingmachineFragment.CustomPopup(getContext());
        new XPopup.Builder(getContext())
                .asCustom(customPopup)
                .show();
    }
    public  class CustomPopup extends CenterPopupView {
        public CustomPopup(@NonNull Context context) {
            super(context);
        }
        @Override
        protected int getImplLayoutId() {
            return R.layout.check_custom_popup;
        }
        @Override
        protected void onCreate() {
            super.onCreate();
            TextView textView;
            textView=findViewById(R.id.check_dialog_sn);
            textView.setText(bing_inputsn.getText().toString());
             findViewById(R.id.check_close).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                  dismiss();
                }
            });
            findViewById(R.id.check_dialog_button).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
        protected void onShow() {
            super.onShow();
        }
    }

    private void dialog_fail_show() {
        BingmachineFragment.FailCustomPopup customPopup = new BingmachineFragment.FailCustomPopup(getContext());
        new XPopup.Builder(getContext())
                .asCustom(customPopup)
                .show();
    }
    public  class FailCustomPopup extends CenterPopupView {
        public FailCustomPopup(@NonNull Context context) {
            super(context);
        }
        @Override
        protected int getImplLayoutId() {
            return R.layout.check_custom_popup_fail;
        }
        @Override
        protected void onCreate() {
            super.onCreate();
            TextView textView;
            textView=findViewById(R.id.check_dialog_sn_fail);
            textView.setText(bing_inputsn.getText().toString());
            findViewById(R.id.check_close_fail).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
            findViewById(R.id.check_dialog_button_fail).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
        protected void onShow() {
            super.onShow();
        }
    }




    public static final String KEY_TITLE = "key_title";
    public static final String KEY_IS_QR_CODE = "key_code";
    public static final String KEY_IS_CONTINUOUS = "key_continuous_scan";

    public static final int REQUEST_CODE_SCAN = 0X01;
    public static final int REQUEST_CODE_PHOTO = 0X02;

    public static final int RC_CAMERA = 0X01;

    public static final int RC_READ_PHOTO = 0X02;

    private Class<?> cls;
    private String title;
    private boolean isContinuousScan;



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && data!=null){
            switch (requestCode){
                case REQUEST_CODE_SCAN:
                    String result = data.getStringExtra(Intents.Scan.RESULT);
                    bing_inputsn.setText(result);
                    break;
                case REQUEST_CODE_PHOTO:
                    parsePhoto(data);
                    break;
            }

        }
    }

    private void parsePhoto(Intent data){
        final String path = UriUtils.getImagePath(getContext(),data);
        Log.d("Jenly","path:" + path);
        if(TextUtils.isEmpty(path)){
            return;
        }
        //异步解析
        asyncThread(new Runnable() {
            @Override
            public void run() {
                final String result = CodeUtils.parseCode(path);
                bing_inputsn.setText(result);
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Log.d("Jenly","result:" + result);
//                        Toast.makeText(getContext(),result,Toast.LENGTH_SHORT).show();
//                    }
//                });

            }
        });

    }



    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        // Some permissions have been granted

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        // Some permissions have been denied
        // ...
    }

    /**
     * 检测拍摄权限
     */
    @AfterPermissionGranted(RC_CAMERA)
    private void checkCameraPermissions(){
        String[] perms = {Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {//有权限
            startScan(cls,title);
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, getString(R.string.permission_camera),
                    RC_CAMERA, perms);
        }
    }

    private void asyncThread(Runnable runnable){
        new Thread(runnable).start();
    }

    /**
     * 扫码
     * @param cls
     * @param title
     */
    private void startScan(Class<?> cls,String title){
        ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeCustomAnimation(getContext(),R.anim.in,R.anim.out);
        Intent intent = new Intent(getContext(), cls);
        intent.putExtra(KEY_TITLE,title);
        intent.putExtra(KEY_IS_CONTINUOUS,isContinuousScan);
        ActivityCompat.startActivityForResult(getActivity(),intent,REQUEST_CODE_SCAN,optionsCompat.toBundle());
    }








}
